//
//  AddOpenLockWayVC.m
//  AILock
//
//  Created by 谭亚明 on 2020/7/17.
//  Copyright © 2020 tym. All rights reserved.
//

#import "AddOpenLockWayVC.h"
#import "YYModel.h"
#import "UIView+ZFFrame.h"
#import "UnlockingWayVC.h"
#import "EquipmentService.h"
#import "ShowAlertView.h"
#import "UIButton+ImageTitleSpacing.h"
#import "UIButton+Gradient.h"
#import "Sizes.h"
@interface AddOpenLockWayVC ()

@property(nonatomic,strong) EquipmentService *services;

@property(nonatomic,weak) IBOutlet UIButton *alertBtn;
@property(nonatomic,weak) IBOutlet UILabel *titTopLab;
@property(nonatomic,weak) IBOutlet UILabel *titBotLab;

@property(nonatomic,weak) IBOutlet UIButton *saveBtn;

@property(nonatomic,weak) IBOutlet UIImageView *fingerImage;
@property(nonatomic,weak) IBOutlet UIButton *animBtn;


@property(nonatomic,weak) IBOutlet UIView *bigConView;
@property(nonatomic,weak) IBOutlet UIImageView *big2View;
@end

@implementation AddOpenLockWayVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackBtnFunc];
    [self initUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addPasswordCurrAction:) name:@"addPasswordCurrAction" object:nil];
}

-(void)addPasswordCurrAction:(NSNotification *) notification{
    
    self.animBtn.hidden = YES;

    NSDictionary *dataDic = notification.object;
    EquipmentMessage *message = [EquipmentMessage yy_modelWithJSON:dataDic];
    TYMWeak(self);
    if (message.success) {
        
        if (message.packageCur < message.packageAll && [self.equipUserModel.equipmentUserType isEqualToString:@"00"]){
            self.fingerImage.hidden = NO;
            
            NSInteger fingerCur;
            if (message.packageAll == 4) {
                fingerCur = message.packageCur;
            }else {
                fingerCur = message.packageCur/2;
            }            
            NSString *imageName = [NSString stringWithFormat:@"finger_%ld",fingerCur];
            self.fingerImage.image = [UIImage imageNamed:imageName];
        }else{
            
            self.titTopLab.hidden = YES;
            self.titBotLab.hidden = YES;
            
            if ([self.equipUserModel.equipmentUserType isEqualToString:@"00"]) {
                [weakself.alertBtn setTitle:@"指纹添加成功" forState:UIControlStateNormal];
            }else if([self.equipUserModel.equipmentUserType isEqualToString:@"01"]){
                [weakself.alertBtn setTitle:@"卡添加成功" forState:UIControlStateNormal];
            }else if([self.equipUserModel.equipmentUserType isEqualToString:@"02"]){
                [weakself.alertBtn setTitle:@"密码添加成功" forState:UIControlStateNormal];
            }else if([self.equipUserModel.equipmentUserType isEqualToString:@"03"]){
                [weakself.alertBtn setTitle:@"遥控添加成功" forState:UIControlStateNormal];
            }
            [weakself.alertBtn setImage:[UIImage imageNamed:@"icon_ok1"] forState:UIControlStateNormal];
            [weakself.alertBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop imageTitleSpace:10];
            weakself.alertBtn.hidden = NO;
            
            [weakself.saveBtn setTitle:@"确定" forState:UIControlStateNormal];
            weakself.saveBtn.hidden = NO;
            weakself.saveBtn.selected = YES;
            self.fingerImage.hidden = YES;
            
        }
    }else{ //失败了
        weakself.titTopLab.hidden = YES;
        weakself.titBotLab.hidden = YES;
        weakself.fingerImage.hidden = YES;
        weakself.saveBtn.hidden = NO;
        weakself.alertBtn.hidden = NO;
        [weakself.alertBtn setImage:[UIImage imageNamed:@"icon_ok2"] forState:UIControlStateNormal];
        [weakself.alertBtn setTitle:@"操作失败" forState:UIControlStateNormal];
        [weakself.alertBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop imageTitleSpace:10];
        [weakself.saveBtn setTitle:@"重试" forState:UIControlStateNormal];
    }
}

-(void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    
}

-(void)initUI{
    self.saveBtn.layer.masksToBounds = YES;
    self.saveBtn.layer.cornerRadius = 5;
    [self.saveBtn gradientButtonWithSize:CGSizeMake(300, 44) colorArray:@[(id)rgba(139, 175, 255),(id)rgba(76, 132, 255)] percentageArray:@[@(0.5),@(1)] gradientType:GradientFromLeftTopToRightBottom];
    self.saveBtn.hidden = YES;
    self.fingerImage.backgroundColor = viewBGColor;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self updateUI];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    //没有完成 手动结束操作
    if(!self.saveBtn.selected){
        [self getEndingOperation];
    }
}

-(void)updateUI{
    if ([self.equipUserModel.equipmentUserType isEqualToString:@"00"]) {
        [self addTitle:@"添加指纹"];
        self.titTopLab.text = @"请在锁体上按下手指";
        [self.animBtn setImage:[UIImage imageNamed:@"icon_guide2"] forState:UIControlStateNormal];
        [self setupHeartbeatAnimationInView:self.animBtn topValue:ScreenHeight/2-150-18];
    }else if([self.equipUserModel.equipmentUserType isEqualToString:@"01"]){
        [self addTitle:@"添加卡"];
        self.titTopLab.text = @"请在锁体刷卡区刷卡";
        [self.animBtn setImage:[UIImage imageNamed:@"card"] forState:UIControlStateNormal];
        [self setupHeartbeatAnimationInView:self.animBtn topValue:91.0 + SafeTopMargin];
    }else if([self.equipUserModel.equipmentUserType isEqualToString:@"02"]){
        [self addTitle:@"添加密码"];
        self.titTopLab.text = @"请在锁体上输入密码";
        [self.animBtn setImage:[UIImage imageNamed:@"icon_guide2"] forState:UIControlStateNormal];
        [self setupHeartbeatAnimationInView:self.animBtn topValue:70.0 + SafeTopMargin];
    }else if([self.equipUserModel.equipmentUserType isEqualToString:@"03"]){
        [self addTitle:@"添加遥控"];
        self.titTopLab.text = @"请在锁体上遥控操作";
        [self.animBtn setImage:[UIImage imageNamed:@"icon_yaokong-1"] forState:UIControlStateNormal];
        [self setupHeartbeatAnimationInView:self.animBtn topValue:130];
    }
    
}

-(EquipmentService*)services{
    if (_services == nil) {
        _services = [[EquipmentService alloc] init];
    }
    return _services;
}

-(void)addEquipmentUser{
    self.alertBtn.hidden = YES;
    self.saveBtn.hidden = YES;
    self.titTopLab.hidden = NO;
    self.titBotLab.hidden = NO;
    
    TYMWeak(self);
    [self.services getEquipmentAdduserlockequipmentId:self.equipUserModel.equipmentId equipmentUserType:self.equipUserModel.equipmentUserType effectiveTime:self.equipUserModel.effectiveTime userRole:self.equipUserModel.userRole startTime:self.equipUserModel.startTime endTime:self.equipUserModel.endTime
                                                start:self.equipUserModel.start
                                                  end:self.equipUserModel.end validWeek:self.equipUserModel.validWeek type:self.equipUserModel.type userId:self.equipUserModel.equipmentUserId
                                                 name:@""
                                           completion:^(LMJBaseResponse * _Nonnull respons) {
        if (respons.code == 0) {
            self.animBtn.hidden = NO;
        }else {
            [ShowAlertView showAlertViewTitle:@"提示" message:respons.message actionBtnTitle:@"确定"
                                 hiddenCancel:NO
                                   completion:^(NSInteger actionType) {
                if (actionType) {
                    if (respons.code == 2001) {
                        [weakself getVerifyAdminrole];
                    }else{
                        [weakself addEquipmentUser];
                    }
                }else{
                    [weakself  webfailedAction:respons.message];
                }
            }];
        }
    }];
}

-(void)webfailedAction:(NSString*)message{
    [self.saveBtn setTitle:@"重试" forState:UIControlStateNormal];
    self.saveBtn.hidden = NO;
    
    [self.alertBtn setTitle:message forState:UIControlStateNormal];
    [self.alertBtn setImage:[UIImage imageNamed:@"icon_ok2"] forState:UIControlStateNormal];
    [self.alertBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop imageTitleSpace:10];
    
}

//验证管理员
-(void)getVerifyAdminrole{
    TYMWeak(self);
    [self.services getVerifyadminroleEpumentId:self.equipUserModel.equipmentId completion:^(LMJBaseResponse * _Nonnull respons) {
        if (respons.code == 0) {
            [weakself addEquipmentUser];
        }else{
            [weakself webfailedAction:respons.message];
        }
    }];
}

-(void)getEndingOperation{
    
    [self.services getendingoperatinEquipuserId:self.equipUserModel.equipmentId commandType:1 busiType:1 completion:^(LMJBaseResponse * _Nonnull respons) {
        
    }];
}

//底部的按钮
-(IBAction)bottomAction:(UIButton*)sender{
    
    if(sender.selected){ //添加成功
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[UnlockingWayVC class]]) {
                [self.navigationController popToViewController:controller animated:YES];
                
            }
        }
    }else{
        
        [self addEquipmentUser];
    }
}

-(void)setupHeartbeatAnimationInView:(UIView *)animationImageView topValue:(float)topValue{
    
    animationImageView.frame = CGRectMake(ScreenWidth/2, self.saveBtn.zf_top - 100, animationImageView.zf_width,animationImageView.zf_width);
    
    [UIView animateWithDuration:2.6 animations:^{
        animationImageView.frame = CGRectMake(ScreenWidth/2-45, topValue, animationImageView.zf_width,animationImageView.zf_width);
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:0.6 delay:1.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
            animationImageView.frame = CGRectMake(ScreenWidth/2, self.saveBtn.zf_top - 100, animationImageView.zf_width,animationImageView.zf_width);
        } completion:^(BOOL finished) {
          [self setupHeartbeatAnimationInView:self.animBtn topValue:topValue];
        }];
    }];
    
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"addPasswordCurrAction" object:nil];
}


@end
